<?php

namespace App\Http\Controllers\Api;

use App\Models\FreeRecord;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;

class FreeRecordController extends AppBaseController
{

    public function query(Request $request)
    {
        $this->validate($request, [
            'date' => 'required|array',
            'min_time' => 'required|integer',
            'max_time' => 'required|integer',
            'free_times' => 'required|integer',
        ]);

        //接受数据
        $parks = $request->get('park_code', $this->getParkCodes($this->getUserParks()));
        $date =  $request->get('date');
        $max_time = $request->get('max_time') * 60;
        $min_time = $request->get('min_time') * 60;
        $start_time = strtotime(str_replace('+',' ',$date[0]));
        $end_time = strtotime(str_replace('+',' ',$date[1]));
        $free_times = $request->get('free_times');
        $query = FreeRecord::where('parking_duration', '>=', $min_time)
            ->where('parking_duration', '<=', $max_time)
            ->whereIn('park_code', $parks)
            ->where('out_time', '>=', $start_time)
            ->where('out_time', '<', $end_time)
            ->select(
                'vpl_number',
                \DB::raw('COUNT(*) AS times')
            )
            ->groupBy('vpl_number')
            ->havingRaw(' COUNT(*) >= ' . $free_times)
            ->get();

        //构建数据
        $res = $query->groupBy('times');
        $data = $res->map(function ($item, $key) {
            $v = [];
            $v['free_times'] = $key;
            $v['free_car'] = $item->count();
            $v['car_count'] = $item->toArray();

            return $v;
        });

        //排序
        $response = $data->sortByDesc('free_times')->toArray();
        array_unshift($response, [
            'free_times' => '合计(>=' . $free_times . ')',
            'free_car' => $data->sum('free_car')
        ]);

        return $this->sendResponse($response, '请求成功');
    }
}
